//
//  YWUnfinishKeepWatchTableViewController.m
//  maintain
//
//  Created by Kyo on 16/9/22.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "YWUnfinishKeepWatchTableViewController.h"
#import "UIColor+CustomColors.h"
#import "UIScrollView+EmptyDataSet.h"
#import "MJRefresh.h"
#import "YWMacro.h"
#import "YWConst.h"
#import "YWCommonTool.h"

#import "UITableView+FDTemplateLayoutCell.h"
#import "YWUnfinishKeepWatchMIssionCell.h"

#import "YWKeepWatchMissionManager.h"
#import "YWNotifyManager.h"

#import "YWKeepWatchViewController.h"
#import "YWEwinManager.h"
//#import "YWReplyManager.h"
//#import "YWNoReadReplyTableViewController.h"

@interface YWUnfinishKeepWatchTableViewController ()<DZNEmptyDataSetDelegate, DZNEmptyDataSetSource>{
    NSInteger page;
    BOOL needReload;
}
@property (nonatomic, strong) NSArray* keepWatchMissions;
@end

@implementation YWUnfinishKeepWatchTableViewController
//- (instancetype)init{
//    return [super initWithStyle:UITableViewStyleGrouped];
//}

- (void)viewDidLoad {
    [super viewDidLoad];
    page = 1;
    self.view.backgroundColor = [UIColor customBackgroudColor];
    
    [self setupNotifications];
    [self setupTableView];
//    NSString *keepWatchMissionIds = [[YWKeepWatchMissionManager shareManager] allKeepWatchMissionIds];
//    [[YWKeepWatchMissionManager shareManager] requestTheLatestLineRecordWithKeepWatchMissionIds:keepWatchMissionIds complete:nil];
}

- (NSArray*)keepWatchMissions
{
    if (!_keepWatchMissions) {
        NSArray* missions = [[NSArray alloc] initWithArray:[[YWKeepWatchMissionManager shareManager] keepWatchMissionsWithPage:page]];
        _keepWatchMissions = missions;
    }
    return _keepWatchMissions;
}

- (void)setupNotifications{
    [[YWNotifyManager shareManager] addReflashPatrolLineViewObserver:self selector:@selector(refreshPatrolLineView)];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshTableView) name:KRefreshAssignKeepWatchMissionNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshTableView) name:KRefreshModifyKeepWatchMissionNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshTableView) name:KRefreshDeleteKeepWatchMissionNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshTop) name:KRefreshModifyPatrolLineNotification object:nil];
}

- (void)setupTableView{
    [self.tableView registerClass:[YWUnfinishKeepWatchMIssionCell class] forCellReuseIdentifier:YWUnfinishKeepWatchMIssionCellIdentifier];
    self.tableView.sectionFooterHeight = 0.01f;
    self.tableView.emptyDataSetDelegate = self;
    self.tableView.emptyDataSetSource = self;
    self.tableView.backgroundColor = [UIColor customBackgroudColor];
    self.tableView.tableFooterView = [[UIView alloc] init];
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, KbottomViewH, 0);
    self.tableView.estimatedRowHeight = 150.0f;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshTop)];
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(refreshFootor)];
    self.tableView.mj_footer.automaticallyHidden = YES;
    // 马上进入刷新状态
    [self.tableView.mj_header beginRefreshing];
}
- (void)refreshTop{
    page = 1;
    [self.tableView.mj_footer resetNoMoreData];
    [self requestData:YWTableViewFreshTypeDown];
}

- (void)refreshFootor{
    [self requestData:YWTableViewFreshTypeUp];
}

- (void)requestData:(YWTableViewFreshType)refreshType{
    if (refreshType == YWTableViewFreshTypeUp) {
        page++;
    }
    YWWeakSelf(weakSelf);
    [[YWKeepWatchMissionManager shareManager] requestKeepWatchMissionPage:page pageSize:10 WithComplete:^(BOOL success) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (success) {
                //请求巡更路线
                [weakSelf requestPatrolLineComplete:^(BOOL success) {
                    if (refreshType == YWTableViewFreshTypeDown) {
                        [weakSelf.tableView.mj_header endRefreshing];
                    }else {
                        [weakSelf.tableView.mj_footer endRefreshing];
                    }
                    weakSelf.keepWatchMissions = nil;
                    [weakSelf.tableView reloadData];
                }];
                
                NSTimeInterval currentTime = [[NSDate date] timeIntervalSince1970]*1000;
                [[YWEwinManager shareManager] saveLastReadTime:currentTime type:YWUnReadCountTypeKeepWatch];
            }else{
                if (refreshType == YWTableViewFreshTypeDown) {
                    [weakSelf.tableView.mj_header endRefreshing];
                }else {
                    [weakSelf.tableView.mj_footer endRefreshing];
                }
            }
        });
    }];
}

- (void)requestPatrolLineComplete:(void (^)(BOOL))complete{
    NSArray *patrolLineArray = [[YWKeepWatchMissionManager shareManager] needRequestPatrolLines];
    if (patrolLineArray.count) {
        [[YWKeepWatchMissionManager shareManager] requestPatrolLineWithLineArray:patrolLineArray complete:^(BOOL success) {
            if (complete) {
                complete(success);
            }
        }];
    }else{
        if (complete) {
            complete(NO);
        }
    }
}

#pragma mark - UITableViewDataSource
//- (CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath
//{
//    YWKeepWatchMission* mission = self.keepWatchMissions[indexPath.section];
//    return [tableView fd_heightForCellWithIdentifier:YWUnfinishKeepWatchMIssionCellIdentifier cacheByIndexPath:indexPath configuration:^(YWUnfinishKeepWatchMIssionCell *cell) {
//        cell.fd_enforceFrameLayout = NO;
//        cell.keepWatchMission = mission;
//    }];
//}

- (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView
{
    return self.keepWatchMissions.count;
}

- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
{
    YWUnfinishKeepWatchMIssionCell* cell = [tableView dequeueReusableCellWithIdentifier:YWUnfinishKeepWatchMIssionCellIdentifier];
    YWKeepWatchMission* mission = self.keepWatchMissions[indexPath.section];
    cell.fd_enforceFrameLayout = NO;
    cell.keepWatchMission = mission;
    return cell;
}
- (void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    YWKeepWatchViewController* kwvc = [[YWKeepWatchViewController alloc] init];
    YWKeepWatchMission* mission = self.keepWatchMissions[indexPath.section];
    kwvc.keepWatchMission = mission;
    [self.navigationController pushViewController:kwvc animated:YES];
}

#pragma mark - UITableViewDataDelegate
- (CGFloat)tableView:(UITableView*)tableView heightForHeaderInSection:(NSInteger)section
{
    return 35;//10;
}

#pragma mark - table view section header view

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    static NSString* HeaderIdentifier = @"YWUnfinishKeepWatchMissionTableViewControllerForHeaderInSection";
    UITableViewHeaderFooterView* headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:HeaderIdentifier];
    if (headerView == nil) {
        headerView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:HeaderIdentifier];
        headerView.contentView.backgroundColor = [UIColor customBackgroudColor];
        UILabel* label = [[UILabel alloc] init];
        label.textAlignment = NSTextAlignmentLeft;
        label.textColor = [UIColor customYellowColor];
        label.tag = 2016;
        label.font = KTitleFont;
        [headerView addSubview:label];
    }
    
    NSString *headText = [self titleForHeaderInSection:section];
    UILabel* label = [headerView viewWithTag:2016];
    label.text = headText;
    label.frame = CGRectMake(15, 0, SCREEN_WIDTH - 2 * 15, 35);
    return headerView;
    
}

- (NSString *)titleForHeaderInSection:(NSInteger)section{
    YWKeepWatchMission* keepWatchMission = self.keepWatchMissions[section];
    NSString *lineName = keepWatchMission.patrolLine.patrolLineName?keepWatchMission.patrolLine.patrolLineName:@"";
    return lineName;
}

- (void)refreshPatrolLineView{
    needReload = YES;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (needReload) {
        needReload = NO;
        _keepWatchMissions = nil;
        [self.tableView reloadData];
    }
}

- (void)refreshTableView{
    needReload = YES;
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
